package com.kun.kunkunmall.member.service.impl;

import com.kun.kunkunmall.member.entity.MemberLevelEntity;
import com.kun.kunkunmall.member.exception.EmailExistException;
import com.kun.kunkunmall.member.exception.PhoneExistException;
import com.kun.kunkunmall.member.exception.UserNameExistException;
import com.kun.kunkunmall.member.service.MemberLevelService;
import com.kun.kunkunmall.member.vo.GiteeUserVo;
import com.kun.kunkunmall.member.vo.MemberLoginVo;
import com.kun.kunkunmall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.utils.PageUtils;
import com.kun.common.utils.Query;

import com.kun.kunkunmall.member.dao.MemberDao;
import com.kun.kunkunmall.member.entity.MemberEntity;
import com.kun.kunkunmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo registerVo) {
        MemberEntity memberEntity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        // 检查用户名和手机号的唯一性，为了让controller能够感知到那里不唯一，使用异常机制
        checkPhoneUnique(registerVo.getPhone());
        checkUserNameUnique(registerVo.getUserName());
        // 设置手机号
        memberEntity.setMobile(registerVo.getPhone());
        // 设置用户名
        memberEntity.setUsername(registerVo.getUserName());
        memberEntity.setNickname(registerVo.getUserName());
        // 设置密码，不能设置明文，要加密传输
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(registerVo.getPassword());
        memberEntity.setPassword(encodePassword);
        // 保存
        baseMapper.insert(memberEntity);
    }

    /**
     * 检查邮箱唯一性
     *
     * @param email
     * @return
     */
    @Override
    public void checkEmailUnique(String email) throws EmailExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("email", email));
        if (count > 0) {
            throw new EmailExistException();
        }
    }

    /**
     * 检查用户名字唯一性
     *
     * @param userName
     * @return
     */
    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameExistException();
        }

    }

    /**
     * 检查电话唯一性
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        // 1. 根据账号和密码从数据库中查询
        String loginAccount = loginVo.getLoginAccount();
        String password = loginVo.getPassword();

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginAccount).or()
                .eq("mobile", loginAccount));

        if (memberEntity == null) {
            // 数据库中没有，登陆失败
            return null;
        } else {
            // 校验密码
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                // 用户输入密码和数据库匹配成功
                return memberEntity;
            } else {
                return null;
            }
        }
    }


    @Override
    public MemberEntity oauth2Login(GiteeUserVo giteeUserVo) {
        // 判断当前社交用户是否已经登录过系统
        MemberEntity social_uid_gitee = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid_gitee", giteeUserVo.getId()));
        if (social_uid_gitee != null) {
            // 用户已经注册，需要重新更换令牌信息
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(social_uid_gitee.getId());
            memberEntity.setAccessToken(giteeUserVo.getAccess_token());
            memberEntity.setExpiresIn(giteeUserVo.getExpires_in());
            memberEntity.setSocialUidGitee(social_uid_gitee.getSocialUidGitee());
            this.updateById(memberEntity);

            social_uid_gitee.setAccessToken(giteeUserVo.getAccess_token());
            social_uid_gitee.setExpiresIn(giteeUserVo.getExpires_in());
            return social_uid_gitee;
        } else {
            // 没有查到当前社交用户对应的记录，我们就需要注册
            MemberEntity register = new MemberEntity();
            // 查询当前社交用户的账号信息，性别，昵称等等
            String name = giteeUserVo.getName();
            String email = giteeUserVo.getEmail();
            String avatar_url = giteeUserVo.getAvatar_url();
            try {
                register.setNickname(name);
                register.setEmail(email);
                register.setHeader(avatar_url);
            }catch (Exception e){}

            register.setAccessToken(giteeUserVo.getAccess_token());
            register.setExpiresIn(giteeUserVo.getExpires_in());
            register.setSocialUidGitee(giteeUserVo.getId());
            this.baseMapper.insert(register);
            return register;
        }
    }

}